﻿using System;
using System.Collections.Generic;
using UnityEngine;

public class TimeComponent : MonoBehaviour
{
    public object param;
    public long id;
    public Action<object> callBack;

    public void SetInterval(Action<object> callBack,long id, float time,float repeatRate, object param = null)
    {
        this.callBack = callBack;
        this.id = id;
        this.param = param;
        InvokeRepeating("OnRepeating", time, repeatRate);
    }
    public void SetTimeout(Action<object> callBack, long id, float time, object param = null)
    {
        this.callBack = callBack;
        this.id = id;
        this.param = param;
        Invoke("OnInvoke", time);
    }
    void OnRepeating()
    {
        callBack?.Invoke(param);
    }
    void OnInvoke()
    {
        CancelInvoke("OnInvoke");
        callBack?.Invoke(param);
    }
}
[XLua.LuaCallCSharp]
public class GameTime : Singleton<GameTime>
{
    private long _timeID = 0;
    private Dictionary<long, TimeComponent> timCompList=new Dictionary<long, TimeComponent>();
    public long SetInterval(Action<object> callBack,float time, float repeatRate, object param = null)
    {
        _timeID++;
        TimeComponent timeComponent=this.gameObject.AddComponent<TimeComponent>();
        timeComponent.SetInterval(callBack, _timeID, time, repeatRate, param);
        timCompList.Add(_timeID, timeComponent);
        return _timeID;
    }
    public long SetTimeout(Action<object> callBack, float time, object param = null)
    {
        _timeID++;
        TimeComponent timeComponent = this.gameObject.AddComponent<TimeComponent>();
        timeComponent.SetTimeout(callBack, _timeID, time, param);
        timCompList.Add(_timeID, timeComponent);
        return _timeID;
    }
    public bool Clear(long id)
    {
        if (timCompList.ContainsKey(id))
        {
            Destroy(timCompList[id]);
            timCompList.Remove(id);
            return true;
        }
        return false;
    }
}